import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

// 定义路由表
const routes = [
  // 重定向
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    component: () => import("../views/Home"),
    children: [
      {
        path: "/home",
        redirect: "/home/movie",
      },
      {
        path: "/home/movie",
        component: () => import("../views/home/Movie"),
        children: [
          {
            path: "/home/movie",
            redirect: "/home/movie/hot",
          },
          {
            path: "/home/movie/hot",
            component: () => import("../components/home/hot/MyList"),
            meta: {
              requireAlive: true,
            },
          },
          {
            path: "/home/movie/cinema",
            component: () => import("../components/home/cinema/Cinema"),
            meta: {
              requireAlive: true,
            },
          },
          {
            path: "/home/movie/wait",
            component: () => import("../components/home/wait/Wait"),
            meta: {
              requireAlive: false,
            },
          },
          {
            path: "/home/movie/classic",
            component: () => import("../components/home/classic/Classic"),
            meta: {
              requireAlive: true,
            },
          },
        ],
      },
      {
        path: "/home/video",
        component: () => import("../views/home/Video"),
      },
      {
        path: "/home/mini",
        component: () => import("../views/home/Mini"),
      },
      {
        path: "/home/show",
        component: () => import("../views/home/Show"),
      },
      {
        path: "/home/mine",
        component: () => import("../views/home/Mine"),
        // 路由独享守卫，路由鉴权
        // beforeEnter: (to, from, next) => {
        //   if (localStorage.getItem("token")) {
        //     next();
        //   } else {
        //     next("/login");
        //   }
        // },
        // 路由元信息
        meta: {
          // 说明此页面需要登录
          requireLogin: true,
        },
      },
    ],
  },
  {
    path: "/city",
    component: () => import("../views/City"),
  },
  {
    path: "/detail/:id",
    component: () => import("../views/Detail"),
    props: true,
  },
  {
    path: "/login",
    component: () => import("../views/Login"),
  },
  // 404页面
  {
    path: "*",
    component: () => import("../views/NotFound"),
  },
];

// 定义路由实例
const router = new VueRouter({
  routes,
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 需要登录
  if (to.meta.requireLogin) {
    if (localStorage.getItem("token")) {
      next();
    } else {
      next("/login");
    }
  } else {
    next();
  }
});

// 用于解决router重复点击的报错
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

// 暴露路由实例
export default router;
